package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/urfave/cli"
)

/*
签到
go run main.go  signin -f myforum -u myusername -p mypassword
//完成任务
go run main.go dailytask
*/
func main() {
	app := cli.NewApp()
	app.Name = "Forum Sign-in"
	app.Usage = "一个简单的论坛签到工具"

	app.Commands = []cli.Command{
		{
			Name:    "signin",
			Aliases: []string{"s"},
			Usage:   "在论坛签到",
			Action:  signIn,
			//用来在signIn中接收参数以及参数用途。
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "forum, f",
					Usage: "要去签到的论坛名字",
				},
				cli.StringFlag{
					Name:  "username, u",
					Usage: "你的用户名",
				},
				cli.StringFlag{
					Name:  "password, p",
					Usage: "用户密码",
				},
			},
		},
		{
			Name:    "dailytask",
			Aliases: []string{"d"},
			Usage:   "完成每日任务",
			Action:  completeDailyTask,
		},
	}

	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
}

func signIn(c *cli.Context) error {
	forum := c.String("forum")
	username := c.String("username")
	password := c.String("password")

	if forum == "" || username == "" || password == "" {
		fmt.Println("Please provide forum, username, and password")
		return nil
	}

	// Simulate sign-in by printing to console
	fmt.Printf("Signed in to %s as %s\n", forum, username)

	// Log the sign-in action
	logToFile("Signed in to " + forum + " as " + username)

	return nil
}

func completeDailyTask(c *cli.Context) error {
	// 打印任务完成
	fmt.Println("Completed daily tasks")

	//将字符串 "Completed daily tasks" 作为参数传递给它。logToFile 函数会将传入的消息追加写入到日志文件中
	logToFile("Completed daily tasks")

	return nil
}

func logToFile(message string) {
	//os.O_APPEND：将写入的数据追加到文件末尾。
	//os.O_CREATE：如果文件不存在，则创建文件。
	//os.O_WRONLY：以只写模式打开文件。
	file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	logger := log.New(file, "", log.LstdFlags)
	//logger.Println() 函数将当前时间（使用 time.Now().Format(time.RFC3339)）和传入的消息写入到日志文件中，以一行的形式记录日志。
	logger.Println(time.Now().Format(time.RFC3339), message)
}
